package com.spring.dao.impl;

import com.spring.dao.AccountDao;
import com.spring.domain.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class AccountDaoImpl implements AccountDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void save(Account account) {
        String sql = "insert into account values(null,?,?)";

        jdbcTemplate.update(sql,account.getName(),account.getMoney());
    }

    @Override
    public Account findById(int id) {
        String sql = "select * from account where id = ?";
        return jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<>(Account.class), id);
    }

    @Override
    public void update(Account account) {
        String sql = "update account set money = ? where name = ?";
        jdbcTemplate.update(sql, account.getMoney(), account.getName());
    }

    @Override
    public void deleteById(int id) {
        String sql = "delete from account where id = ?";
        jdbcTemplate.update(sql, id);
    }

    @Override
    public List<Account> findAll() {
        String sql = "select * from account";
        return jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(Account.class));
    }

    @Override
    public List<Account> findAllWithAlias() {
        String sql = "select id, name AS NPC, money from account";
        return jdbcTemplate.query(sql, new RowMapper<Account>() {
            @Override
            public Account mapRow(ResultSet resultSet, int i) throws SQLException {
                Account account = new Account();
                int id = resultSet.getInt("id");
                account.setId(id);
                String name = resultSet.getString("NPC");
                account.setName(name);
                double money = resultSet.getDouble("money");
                account.setMoney(money);
                return account;
            }
        });
    }

    @Override
    public void update(String name, double money) {
        String sql = "update account set money = money + ? where name = ?";
        jdbcTemplate.update(sql, money, name);
    }
}
